import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { NextRequest } from 'next/server';

export async function GET() {
  try {
    // 从数据库获取所有分类
    const categories = await prisma.category.findMany({
      select: {
        categoryId: true,
        categoryName: true,
        categoryCode: true,
        categoryField: true,
        _count: {
          select: {
            commodities: true
          }
        }
      }
    });

    // 格式化数据以包含商品数量
    const formattedCategories = categories.map(category => ({
      categoryId: category.categoryId,
      categoryName: category.categoryName,
      categoryCode: category.categoryCode,
      categoryField: category.categoryField,
      commodityCount: category._count.commodities
    }));

    return NextResponse.json({ categories: formattedCategories }, { status: 200 });
  } catch (error) {
    console.error('获取分类数据失败:', error);
    return NextResponse.json(
      { error: '获取分类数据失败' },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const categoryId = searchParams.get('id');
    
    if (!categoryId) {
      return NextResponse.json(
        { error: '缺少分类ID参数' },
        { status: 400 }
      );
    }
    
    const body = await request.json();
    const { categoryName, categoryCode, categoryField } = body;
    
    // 验证必要字段
    if (!categoryName) {
      return NextResponse.json(
        { error: '分类名称不能为空' },
        { status: 400 }
      );
    }
    
    // 更新分类
    const updatedCategory = await prisma.category.update({
      where: { categoryId: parseInt(categoryId) },
      data: {
        categoryName,
        categoryCode,
        categoryField
      }
    });
    
    return NextResponse.json(updatedCategory, { status: 200 });
  } catch (error) {
    console.error('更新分类失败:', error);
    return NextResponse.json(
      { error: '更新分类失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { categoryName, categoryCode, categoryField } = body;

    // 验证必要字段
    if (!categoryName) {
      return NextResponse.json(
        { error: '分类名称不能为空' },
        { status: 400 }
      );
    }

    // 创建新分类
    const newCategory = await prisma.category.create({
      data: {
        categoryName,
        categoryCode,
        categoryField: categoryField || 0
      }
    });

    return NextResponse.json({ category: newCategory }, { status: 201 });
  } catch (error) {
    console.error('创建分类失败:', error);
    return NextResponse.json(
      { error: '创建分类失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // 从URL获取分类ID
    const id = request.nextUrl.searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { error: '分类ID不能为空' },
        { status: 400 }
      );
    }
    
    const categoryId = parseInt(id);
    
    // 检查该分类是否有关联的商品
    const category = await prisma.category.findUnique({
      where: { categoryId },
      include: { _count: { select: { commodities: true } } }
    });
    
    if (!category) {
      return NextResponse.json(
        { error: '分类不存在' },
        { status: 404 }
      );
    }
    
    if (category._count.commodities > 0) {
      return NextResponse.json(
        { error: '该分类下有关联商品，无法删除' },
        { status: 400 }
      );
    }
    
    // 删除分类
    await prisma.category.delete({
      where: { categoryId }
    });
    
    return NextResponse.json(
      { message: '分类删除成功' },
      { status: 200 }
    );
  } catch (error) {
    console.error('删除分类失败:', error);
    return NextResponse.json(
      { error: '删除分类失败' },
      { status: 500 }
    );
  }
}